<template>
    <div class="production-plan">
      <!-- <el-button type="success" @click="addjihau" class="save-button">保存主表单和明细</el-button> -->
      <h3 class="title">质检工单信息修改</h3>
      <el-tag :type="formData.status === '已完成' ? 'success' : 
                    formData.status === '质检中' ? 'warning' : 
                    'danger'" class="status-tag">
            {{ formData.status }}
      </el-tag>
      <!-- 基本信息 -->
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="120px"
               class="form-container">
        <el-row :gutter="30">
          <!-- 第一行 -->
          <el-col :span="8">
            <el-form-item label="质检工单主题" style="margin-bottom: 20px;">
              <el-input v-model="formData.qualityWorkOrder" placeholder="请输入质检工单主题"/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质检工单编号" style="margin-bottom: 20px;">
              <el-input v-model="formData.qualityWorkOrderNumber" placeholder="请输入质检工单编号"/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="来源工单" style="margin-bottom: 20px;">
              <el-input v-model="formData.sourceWorkOrder" placeholder="请输来源工单"/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产物品" style="margin-bottom: 20px;">
              <el-input v-model="formData.generateItems" placeholder="请输生产物品"/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质检负责人" style="margin-bottom: 20px;">
              <el-input v-model="formData.qualityPerson" placeholder="请输入质检负责人"/> <!-- 修改了 placeholder -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质检部门">
              <el-select v-model="formData.qualityDepartment" placeholder="选择质检部门">
                <el-option label="包装部" value="包装部"/>
                <el-option label="生产部" value="生产部"/>
                <el-option label="酵母部" value="酵母部"/>
                <el-option label="原料部" value="原料部"/>
                <el-option label="发酵部" value="发酵部"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工序数量" style="margin-bottom: 20px;">
              <el-input v-model="formData.processQuantity" placeholder="请输入"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注信息" style="margin-bottom: 20px;">
              <el-input v-model="formData.remarks" placeholder="请输入" type="textarea" />
            </el-form-item>
          </el-col>
          <el-form-item>
          <el-button type="primary" @click="submitQualityReport">提交质检结果</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
        </el-row>
      </el-form>
  
       <div id="app">
            <el-card>
            <template #header>
                <div class="flex justify-between items-center">
                <span>MinIO 文件上传</span>
                </div>
            </template>
            <el-form ref="formRef1" :model="formData1" label-width="100px">
                <el-form-item label="选择文件">
                <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
                    :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
                    <el-button type="primary">选择文件</el-button>
                </el-upload>
                </el-form-item>
                <el-form-item>
                <el-button type="primary" @click="submitForm">上传文件</el-button>
                </el-form-item>
            </el-form>
            <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
            </el-card>
            <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="key" label="文件名称" width="200" />
            <el-table-column prop="lastModified" label="创建时间" width="200">
                <template #default="scope">
                {{ new Date(scope.row.lastModified).toLocaleString() }}
                </template>
            </el-table-column>
            <el-table-column prop="size" label="文件大小" min-width="200" />
            <el-table-column fixed="right" label="操作" min-width="200">
                <template #default="scope">
                <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
                    删除文件
                </el-button>
                <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
                </template>
            </el-table-column>
            </el-table>
            <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
            <p>确定要删除该文件吗？</p>
            <template #footer>
                <el-button @click="closeDeleteDialog">取消</el-button>
                <el-button type="primary" @click="confirmDelete">确定</el-button>
            </template>
            </el-dialog>
            <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
            <template #content>
                <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
            </template>
            <template #footer>
                <el-button @click="closeDownloadDialog">关闭</el-button>
            </template>
            </el-dialog>
        </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import axios from 'axios';
  import { th } from 'element-plus/es/locales.mjs';
  
  const formRef = ref(null);
  const currentUser = ref("admin");
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({
        "qualityid":  route.params.qualityid,
        "qualityWorkOrder": "",
        "qualityWorkOrderNumber": "",
        "sourceWorkOrder": "",
        "generateItems": "",
        "qualityPerson": "",
        "qualityDepartment": "",
        "processQuantity": '',
        "status": "质检中",  // Set default status to 质检中 when editing
        "remarks": "",
        "isDel": true
  });





const getProductionById = (qualityid) => {
console.log('查看专检申请反填数据:', qualityid);
Materialread.get('f-read/api/Arrival/FTQualityLnspection', {
    params:{
        Qualityid: route.query.qualityid
    }
  })
  .then(res=>{
    formData.qualityid = res.data.data[0].qualityid;
    formData.qualityWorkOrder = res.data.data[0].qualityWorkOrder;
    formData.qualityWorkOrderNumber = res.data.data[0].qualityWorkOrderNumber;
    formData.sourceWorkOrder = res.data.data[0].sourceWorkOrder;
    formData.generateItems = res.data.data[0].generateItems;
    formData.qualityPerson = res.data.data[0].qualityPerson;
    formData.qualityDepartment = res.data.data[0].qualityDepartment;
    formData.processQuantity = res.data.data[0].processQuantity;
    formData.remarks = res.data.data[0].remarks;
    // When editing, set status to 质检中
    formData.status = "质检中";
    formData.modelValue = res.data.data[0];
    console.log('专检申请反填数据:', res.data);
  })
};

 // 提交质检结果
 const submitQualityReport = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        // Update status to 已完成 when submitting
        formData.status = '已完成';
        
        ElMessageBox.confirm(
          '确认提交质检结果？提交后将更新工单状态为已完成。',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          Materialwrite.post('f-write/api/Arrival/UpdateQualityLnspection', formData)
            .then(response => {
              if (response.data.code === 200) {
                ElMessage.success('质检结果提交成功，状态已更新为已完成');
                router.push("/GetQualityLnspection");
              } else {
                ElMessage.error(`提交失败：${response.data.message}`);
              }
            })
            .catch(error => {
              console.error('保存出错:', error);
              ElMessage.error('保存时出现错误，请检查网络或重试');
            });
        }).catch(() => {
          ElMessage.info('已取消提交');
        });
      } else {
        ElMessage.error('请填写完整且正确的质检信息');
        return false;
      }
    });
  };
// // // 保存主表单
//  const addjihau = () => {
//     axios.post('', formData)
//     .then(response => {
//      if (response.data.code === 200) {
//        ElMessage.success('专检申请修改成功');
//        console.log(response.data.data);
//        router.push("/GetQualityLnspection");
//     } else {
//        ElMessage.error(`专检申请修改失败：${response.data.message}`);
//     }
//     })
// };

onMounted(()=>{
  getProductionById();
})


  const fileList = ref([]);

// 上传前校验
const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type);

  if (!isValidType) {
    ElMessage.error('只能上传JPG/PNG/PDF文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!');
    return false;
  }
  return true;
};

// 上传成功
const handleSuccess = (response, file, fileListArr) => {
  if (response.code === 200) {
    ElMessage.success('文件上传成功');
    // 可在此处处理后端返回的文件信息
  } else {
    ElMessage.error('文件上传失败');
  }
};

// 删除文件
const handleRemove = (file, fileListArr) => {
  // 可在此处处理删除逻辑
};


const formRef1 = ref(null);
const uploadRef = ref(null);
const formData1 = ref({});
const message = ref('');
const messageType = ref('');
const tableData = ref([{
  key: "",
  lastModified: "",
  eTag: "",
  size: 0,
  isDir: false,
  versionId: null,
  contentType: null,
  expires: null,
  userMetadata: null,
  isLatest: false,
  lastModifiedDateTime: "",
}]);
const isDeleteDialogVisible = ref(false);
const currentDeleteKey = ref('');
const isDownloadDialogVisible = ref(false);
const downloadProgress = ref(0);
const downloadStatus = ref('');

onMounted(() => {
  listObjects();
});

const download = async (key) => {
  isDownloadDialogVisible.value = true;
  downloadProgress.value = 0;
  downloadStatus.value = 'active';
  try {
    const response = await axios.get(`/api/FileUpload/DownloadFile?objectName=${key}`, {
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        downloadProgress.value = percentCompleted;
      }
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', key);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    downloadStatus.value = 'success';
  } catch (error) {
    console.error('文件下载失败:', error);
    message.value = '文件下载失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
    downloadStatus.value = 'exception';
  }
};

const listObjects = async () => {
  axios.get("https://localhost:7212/api/FileUpload/ListObjectsInOneBucket")
    .then((res) => {
      tableData.value = res.data;
      console.log("查询成功", res.data);
    })
    .catch((err) => {
      console.log(err);
    });
};

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  const response = await axios.post(options.action, formData, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data != null) {
    alert("添加成功");
    return;
  } else {
    alert("添加失败");
    return;
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
};

const submitForm = () => {
  uploadRef.value.submit();
};

const openDeleteDialog = (key) => {
  currentDeleteKey.value = key;
  isDeleteDialogVisible.value = true;
};

const closeDeleteDialog = () => {
  isDeleteDialogVisible.value = false;
  currentDeleteKey.value = '';
};

const confirmDelete = () => {
  axios.delete("https://localhost:7212/api/FileUpload/DeleteObjectInOneBucket", {
    params: {
      objectName: currentDeleteKey.value
    }
  })
    .then((res) => {
      console.log("删除成功", res.data);
      message.value = '文件删除成功';
      messageType.value = 'success';
      listObjects();
      closeDeleteDialog();
    })
    .catch((err) => {
      console.log(err);
      message.value = '文件删除失败: ' + (err.response?.data?.error || err.message);
      messageType.value = 'error';
      closeDeleteDialog();
    });
};

const closeDownloadDialog = () => {
  isDownloadDialogVisible.value = false;
  downloadProgress.value = 0;
  downloadStatus.value = '';
};


    </script>
    
    <style scoped>
    .production-plan {
      padding: 30px;
      background-color: #f0f2f5;
      border-radius: 10px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      font-family: 'Arial', sans-serif;
    }
    
    .title {
      text-align: center;
      margin-bottom: 30px;
      color: #2c3e50;
      font-size: 24px;
      font-weight: 600;
    }
    
    .save-button {
      display: block;
      margin: 0 auto 30px;
      padding: 12px 24px;
      font-size: 16px;
      border-radius: 6px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .form-container {
      background-color: white;
      padding: 30px;
      border-radius: 10px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
    }
    
    .el-form-item__label {
      color: #34495e;
      font-size: 16px;
      font-weight: 500;
    }
    
    .el-input,
    .el-input-number,
    .el-date-picker {
      border-radius: 6px;
      border: 1px solid #ccc;
      padding: 10px;
      font-size: 14px;
      transition: border-color 0.3s ease, box-shadow 0.3s ease;
    }
    
    .el-input:focus,
    .el-input-number:focus,
    .el-date-picker:focus {
      border-color: #42b983;
      outline: none;
      box-shadow: 0 0 5px rgba(66, 185, 131, 0.2);
    }
    .status-tag {
      display: inline-block;
      margin-bottom: 20px;
      padding: 8px 16px;
      font-size: 14px;
      border-radius: 4px;
    }
    </style>